package me.kafeitu.activiti.chapter10;

import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ManagementService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ExecutionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.test.Deployment;
import org.activiti.spring.impl.test.SpringActivitiTestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试callActivity流程
 *
 * @author henryyan
 *
 */
// @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-test-chapter10.xml")
//public class DisposeMessageProcess {
public class DisposeMessageProcess extends SpringActivitiTestCase {
//    @Autowired
//    protected RepositoryService repositoryService;
//    @Autowired
//    protected RuntimeService runtimeService;
//    @Autowired
//    protected TaskService taskService;
//    @Autowired
//    protected FormService formService;
//    @Autowired
//    protected HistoryService historyService;
//    @Autowired
//    protected IdentityService identityService;
//    @Autowired
//    protected ManagementService managementService;

    @Test
    @Deployment(resources = {"diagrams/aecodemsg/dispose-message-process.bpmn"})
    public void testOne() throws Exception {

        identityService.setAuthenticatedUserId("henryyan");

        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("allPeople", "allPeople");
        
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("disposeProcess", variables);
        assertNotNull(processInstance);
        System.out.println("11eid=" + processInstance.getId() + ", pid=" + processInstance.getProcessInstanceId());
        
        // 分发任务
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskCandidateOrAssigned("allPeople").singleResult();
        System.out.println("task = " + task);
        
        // 触发申请任务
        ExecutionQuery executionQuery = runtimeService.createExecutionQuery().messageEventSubscriptionName("MSG_APPLAY");
        Execution execution = executionQuery.singleResult();

        // 触发3个县
        Map<String, Object> variables1 = new HashMap<String, Object>();
        variables1.put("xianUser", "xian1");
        runtimeService.messageEventReceived("MSG_APPLAY", execution.getId(), variables1);
        Map<String, Object> variables2 = new HashMap<String, Object>();
        variables2.put("xianUser", "xian2");
        runtimeService.messageEventReceived("MSG_APPLAY", execution.getId(), variables2);
        Map<String, Object> variables3 = new HashMap<String, Object>();
        variables3.put("xianUser", "xian3");
        runtimeService.messageEventReceived("MSG_APPLAY", execution.getId(), variables3);
        
        // 分配任务到两个市: 1. 县申请->县审核->市子汇总
        List<Task> listApplyXian = taskService.createTaskQuery().taskName("县申请").list();
        for (Task subTaskXian : listApplyXian) {
            Map<String, Object> variablesXian = new HashMap<String, Object>();
            if (subTaskXian.getAssignee().equals("xian3")) {
                variablesXian.put("xianLeader","xianLeader2");
            } else {
                variablesXian.put("xianLeader","xianLeader1");
            }
            
            taskService.complete(subTaskXian.getId(), variablesXian);
        }
        
        // 分配任务到两个市: 2. 县申请->县审核->市子汇总
        List<Task> listXianApprove = taskService.createTaskQuery().taskName("县审核").list();
        for (Task subTaskXianAprrove : listXianApprove) {
            Map<String, Object> variablesXian = new HashMap<String, Object>();
            if (subTaskXianAprrove.getAssignee().equals("xianLeader2")) {
                variablesXian.put("shiLeaderAssis","shiLeaderAssis2");
            } else {
                variablesXian.put("shiLeaderAssis","shiLeaderAssis1");
            }
            
            taskService.complete(subTaskXianAprrove.getId(), variablesXian);
        }
        // 结束 应该是到了两个不同的市
        
        // 这时候市应该看到汇总的任务, 启动 市汇总
        // 得到出发器的运行流
        Execution executionShi = runtimeService.createExecutionQuery().messageEventSubscriptionName("MSG_SHI_COLLECTION").singleResult();
        Map<String, Object> variablesShi1 = new HashMap<String, Object>();
        variablesShi1.put("shiLeaderAssis", "shiLeaderAssis1");
        runtimeService.messageEventReceived("MSG_SHI_COLLECTION", execution.getId(), variablesShi1);
        
        Map<String, Object> variablesShi2 = new HashMap<String, Object>();
        variablesShi2.put("shiLeaderAssis", "shiLeaderAssis2");
        runtimeService.messageEventReceived("MSG_SHI_COLLECTION", execution.getId(), variablesShi2);
        
        // 回退一个县申请
        List<Task> listTaskXian = taskService.createTaskQuery()
                .taskCandidateOrAssigned("shiLeaderAssis1").list(); //.taskDefinitionKey(key);
        
        int rejectCount = 2;
        for (Task subTask:listTaskXian) {
            System.out.println("subTask = " + subTask);
            if (subTask.getTaskDefinitionKey().equals("taskShiSubCollection") && rejectCount-- > 0) {
                Map<String, Object> variablesSub = new HashMap<String, Object>();
                variablesSub.put("shiSubCollectionPass",false);
                taskService.complete(subTask.getId(), variablesSub);
            } 
        }
        
        // 触发省汇总
        Execution executionSheng = runtimeService.createExecutionQuery().messageEventSubscriptionName("MSG_SHENG_COLLECTION").singleResult();
        Map<String, Object> variablesSheng = new HashMap<String, Object>();
        variablesSheng.put("shengLeaderAssis", "shengLeaderAssis");
        runtimeService.messageEventReceived("MSG_SHENG_COLLECTION", execution.getId(), variablesSheng);
        
        // complete 市汇总
//        Map<String, Object> variablesShiLeader = new HashMap<String, Object>();
//        variablesShiLeader.put("shiLeader","dingz");
//        taskService.complete(task.getId(), variablesShiLeader);
//        
//        // shiApprove
//        Task shiApproveTask = taskService.createTaskQuery().processInstanceId(processInstance.getId())
//                .taskCandidateOrAssigned("dingz").singleResult();
//        taskService.complete(shiApproveTask.getId());

        System.out.println("Ended");
    }

}
